import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, register as registerApi } from '@/api/login'

// 认证信息持久化的localStorage键名
const TOKEN_KEY = 'user_token'
const USER_INFO_KEY = 'user_info'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem(TOKEN_KEY) || '')
  const userInfo = ref(JSON.parse(localStorage.getItem(USER_INFO_KEY) || '{}'))
  const isLoading = ref(false)
  const error = ref('')

  // getters
  const isLoggedIn = computed(() => {
    // 增强检查：确保token存在且userInfo不为空对象
    return !!token.value && Object.keys(userInfo.value).length > 0
  })
  const username = computed(() => userInfo.value?.username || '')
  
  // actions
  // 设置token
  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem(TOKEN_KEY, newToken)
  }

  // 设置用户信息
  function setUserInfo(info) {
    userInfo.value = info
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
  }

  // 登录
  async function login(credentials) {
    isLoading.value = true
    error.value = ''
    
    try {
      const response = await loginApi(credentials)
      console.log('登录响应：', response)
      
      if (response.data && response.data.code === 200) {
        const data = response.data.data
        setToken(data.token)
        // 如果响应中包含用户信息，则保存
        if (data.username) {
          setUserInfo({ username: data.username })
        }
        return { success: true, data }
      } else {
        error.value = response.data?.message || '登录失败'
        return { success: false, message: error.value }
      }
    } catch (err) {
      console.error('登录错误:', err)
      error.value = err.response?.data?.message || '服务器连接失败'
      return { success: false, message: error.value }
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  async function register(userData) {
    isLoading.value = true
    error.value = ''
    
    try {
      const response = await registerApi(userData)
      
      if (response.data && response.data.code === 200) {
        const data = response.data.data
        // 如果注册后自动登录，保存token和用户信息
        if (data.token) {
          setToken(data.token)
        }
        if (data.username) {
          setUserInfo({ username: data.username })
        }
        return { success: true, data }
      } else {
        error.value = response.data?.message || '注册失败'
        return { success: false, message: error.value }
      }
    } catch (err) {
      console.error('注册错误:', err)
      error.value = err.response?.data?.message || '服务器连接失败'
      return { success: false, message: error.value, field: err.response?.data?.field }
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  function logout() {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(USER_INFO_KEY)
  }

  // 验证登录状态
  async function validateLogin() {
    // 如果本地没有token或用户信息，直接返回未登录状态
    if (!token.value || Object.keys(userInfo.value).length === 0) {
      return false;
    }
    
    // 在这里可以添加对后端的token验证请求
    // 如果有专门的验证接口，可以在这里调用
    // 例如:
    /*
    try {
      const response = await api.validateToken();
      return response.data?.code === 200;
    } catch (error) {
      console.error('验证登录状态出错:', error);
      // 验证失败，清除本地存储的登录信息
      logout();
      return false;
    }
    */
    
    // 为了演示，这里暂时返回true
    return true;
  }

  return {
    // 状态
    token,
    userInfo,
    isLoading,
    error,
    
    // getters
    isLoggedIn,
    username,
    
    // actions
    setToken,
    setUserInfo,
    login,
    register,
    logout,
    validateLogin
  }
}) 